import { getStsTokenforOss } from '@/api/api.js';
import { Loading } from 'element-ui';
import OSS from 'ali-oss';
export async function ossUploadFile(that, e, uploadName) {
  that.showRentPrise = true;
  let path = {
    COURSE_VEDIOS: 'course/vedios/',
    MATERIAL_RESOURCE: 'material/resource/',
  };
  let res = await getStsTokenforOss({ applicationName: uploadName });
  if (res[0]) {
    return;
  }
  let ossToken = res[1].data;
  let client = new OSS({
    secure: true,
    region: ossToken.region,
    endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    accessKeyId: ossToken.accessKeyId,
    accessKeySecret: ossToken.accessKeySecret,
    bucket: ossToken.bucket,
    stsToken: ossToken.securityToken,
  });
  let uuid = getUuid();
  let suffix = e.file.name.substr(e.file.name.lastIndexOf('.'));
  let filePath = 'niceol/pick-lessons/' + path[uploadName] + uuid + suffix;
  let options = {
    partSize: 10 * 1024 * 1024,
    progress: that.progress,
    mime: 'video/mp4',
  };
  let imgArr = ['.jpg', '.png', '.gif', '.bmp'];
  if (imgArr.indexOf(suffix) !== -1) {
    options['mime'] = 'image/jpeg';
  }
  await client.multipartUpload(filePath, e.file, options);
  that.showRentPrise = false;
  that.percentage = 0;
  let fileUrl =
    ossToken.baseUrl +
    'niceol/pick-lessons/' +
    path[uploadName] +
    uuid +
    suffix;
  return fileUrl;
}

function getUuid() {
  var s = [];
  var hexDigits = '0123456789abcdef';
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4';
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23];
  return s.join('');
}
